<?php

namespace App\Exception\Handler;

use App\Ability\ApiResponse;
use App\Exception\LogicException;
use Hyperf\ExceptionHandler\ExceptionHandler;
use Hyperf\HttpMessage\Stream\SwooleStream;
use Psr\Http\Message\ResponseInterface;
use Throwable;

/**
 * 将逻辑异常转换为标准异常
 */
class LogicExceptionHandler extends ExceptionHandler
{
    use ApiResponse;

    public function handle(\Throwable $throwable, ResponseInterface $response)
    {
        $this->stopPropagation();
        $code = $throwable->getCode();
        $message = $throwable->getMessage();
        $data = [];

        $content = json_encode($this->error($code,$message,$data),JSON_UNESCAPED_UNICODE);

        return $response
            ->withAddedHeader('content-type', 'application/json; charset=utf-8')
            ->withBody(new SwooleStream($content));
    }

    public function isValid(Throwable $throwable): bool
    {
        return $throwable instanceof LogicException;
    }
}